package com.pet.server.ext.action.task;

import java.util.Date;

import net.sf.json.JSONObject;

import com.pet.server.ext.ActionBase;
import com.pet.server.ext.ApiError;
import com.pet.server.ext.BeanToJson;
import com.pet.server.ext.Result;
import com.pet.server.ext.constants.BaseAttribute;
import com.pet.server.ext.constants.Status;
import com.pet.server.ext.constants.Status.DailyTask;
import com.pet.server.ext.constants.Status.NormalTask;
import com.pet.server.ext.data.TaskInfo;
import com.pet.server.ext.data.UserTask;
import com.pet.server.ext.data.UserTaskDaily;
import com.pet.server.ext.service.UserService;
import com.pet.server.ext.util.DateUtil;
import com.pet.server.ext.util.Parameters;

public class Add extends ActionBase{

	private String task_id,task_type;
	public Add(){
		 needCheckAuth =true;
	}
	
	@Override
	public void initParameters(Parameters params) throws ApiError {	
		task_id = params.getFieldValue("task_id");
		task_type =params.getFieldValue("task_type");
	}
	
	@Override
	public Result invokeService() throws ApiError {
		UserService userService = new UserService();
		TaskInfo ti = userService.findTaskInfo(task_id, task_type);
		if(null==ti){
			throw ApiError.Type.LOGIC_ERROR.toException("任务不存在!");		
		}
		Result result = new Result();
		if("normal".equals(task_type)){
			UserTask ut = userService.findUserTask(user.user_id,task_id);
			if(ut==null){
				ut  = new UserTask(user.user_id, 1, BaseAttribute.LOGIC_FALSE, task_id,  BaseAttribute.LOGIC_FALSE, new Date(),ti.task_time,ti.task_integer); 
				userService.saveUserTask(user.user_id,task_id,1);
			}else if(ti.task_time>=ut.time){
				ut.time=ut.time+1;
				userService.addTime4userTask(user.user_id, task_id);
			}
			//判断是否完成
			if(ti.task_time==ut.time){
				ut.is_done=BaseAttribute.LOGIC_TRUE;//
			}
			ut.task_time=ti.task_time;
			ut.task_integer=ti.task_integer;
			JSONObject o = BeanToJson.beanToJson(ut);
			o.put("task_type",task_type);
			result.put("data",o);
		}else if("daily".equals(task_type)){
			String date = DateUtil.getFormatDate(new Date(), "yyyy-MM-dd");
			UserTaskDaily utd = userService.findUserTaskDaily(user.user_id, task_id, date);
			if(utd==null){
				utd = new UserTaskDaily(user.user_id, 1, task_id, BaseAttribute.LOGIC_FALSE, BaseAttribute.LOGIC_FALSE, date,ti.task_time,ti.task_integer);
				userService.saveUserTaskDaily(date, user.user_id,task_id);
			}else if(ti.task_time>=utd.time){
				userService.updateUserTaskDaily(date, user.user_id, date);
				utd.time=utd.time+1;
			}
			//判断是否完成
			if(ti.task_time==utd.time){
				utd.is_done=BaseAttribute.LOGIC_TRUE;
			}
			utd.task_time=ti.task_time;
			utd.task_integer=ti.task_integer;

			JSONObject o = BeanToJson.beanToJson(utd);
			o.put("task_type",task_type);
			result.put("data",o);
		}else{
			throw ApiError.Type.LOGIC_ERROR.toException("任务类型不存在!");	
		}
		//result.put("message", "success");
	    return result;
	}
	
	
	
	
}
